<template>
  <div class="es-counter">
    <!-- 数量 -1 按钮 -->
    <button type="button" class="btn btn-light btn-sm" @click="sub">-</button>
    <!-- 输入框 -->
    <input type="number" class="form-control form-control-sm ipt-num" v-model.number.lazy="num" />
    <!-- 数量 +1 按钮 -->
    <button type="button" class="btn btn-light btn-sm" @click="add">+</button>
  </div>
</template>

<script>
export default {
  name: 'EsCounter',
  props: {
    number: {
      type: Number,
      required: true
    },
    min: {
      type: Number,
      default: NaN
    }
  },
  data() {
    return {
      num: this.number
    };
  },
  emits: ['numChange'],
  watch: {
    num(newval) {
      const parseResult = parseInt(newval);
      if (isNaN(parseResult) || parseResult < 1) {
        this.num = 1;
        return;
      }
      if (String(newval).indexOf('.') !== -1) {
        this.num = parseResult;
        return;
      }
      this.$emit('numChange', this.num);
    }
  },
  methods: {
    // 减少数量
    sub() {
      if (!isNaN(this.min) && this.num - 1 < this.min) return;
      this.num--;
    },
    // 增加数量
    add() {
      this.num++;
    }
  }
};
</script>

<style scoped>
.es-counter {
  display: flex;
}
.btn {
  width: 25px;
}
.ipt-num {
  width: 34px;
  text-align: center;
  margin: 0 4px;
}
</style>